package org.flown.shop.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.flown.shop.SessionAttribute;
import org.flown.shop.dto.SellerDTO;
import org.flown.shop.entity.Seller;
import org.flown.shop.service.SellerService;
import org.flown.shop.service.ServiceResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.PrintWriter;


@RequestMapping("/seller")
@Controller
public class
SellerController
{
    @Autowired
    private SellerService service_seller;


    @ResponseBody
    @RequestMapping({"/getSellerByID", "/{id}"})
    public SellerDTO getSellerByID(@PathVariable @RequestParam int id) {return this.service_seller.getSellerDTOByID(id);}
    @ResponseBody
    @RequestMapping({"/getSellerByAccount", "/account/{account}"})
    public SellerDTO getSellerByAccount(@PathVariable @RequestParam String account) {return this.service_seller.getSellerDTOByAccount(account);}


    @PostMapping(value = "/register", params = {"account", "password"})
    public void register(HttpServletResponse response, @Valid Seller seller)
            throws IOException
    {
        PrintWriter out = response.getWriter();
        if (seller == null) {
            out.println("注册失败");
            out.close();
            return;
        }
        ServiceResult result = this.service_seller.register(seller);
        switch (result) {
            case SUCCESS -> out.println("注册成功");
            case FAILED -> out.println("注册失败");
            case EXISTS -> out.println("账户已存在");
            default -> {
            }
        }
        out.flush();
        out.close();
    }


    @PostMapping(value = "/login", params = {"account", "password"})
    public void login(HttpServletResponse response,
                      HttpSession session,
                      @Valid Seller seller)
            throws IOException
    {
        PrintWriter out = response.getWriter();
        ServiceResult result = this.service_seller.login(seller);
        switch (result) {
            case SUCCESS -> {
                SellerDTO seller_dto = this.getSellerByAccount(seller.getAccount());
                session.setAttribute(SessionAttribute.SELLER.getName(), seller_dto);
                out.println("登录成功");
            }
            case FAILED -> out.println("密码错误");
            case NOT_EXISTS -> out.println("账户不存在");
            default -> {}
        }
        out.flush();
        out.close();
    }



}

